package com.common.util;

import com.hzyzt.seq.dao.SeqRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author fanghu
 *
 */
@Transactional
// (propagation = Propagation.REQUIRES_NEW)
@Service
public class SeqUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(SeqUtil.class);

	@Autowired
	SeqRepository seqRepository;

	public int getAndIncreaseSeq(String key, String area, String date) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		map.put("date", date);
		Integer seq = null;
		try {
			seq = seqRepository.selectOne(map);
		} catch (Exception e) {
			LOGGER.warn("key=" + key + ",date=" + date + ",获取不到seq");
		}

		if (seq == null) {
			seqRepository.insertSeq(map);

			return 1;
		} else {
			seqRepository.updateSeq(map);
			return seq + 1;
		}
	}

	public int getAndIncreaseSeq(String key, String area) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", area);
		map.put("date", "*");

		Integer seq = seqRepository.selectOne(map);
		if (seq == null) {
			seqRepository.insertSeq(map);
			return 0;
		} else {
			seqRepository.updateSeq(map);

			return seq + 1;
		}
	}

	public int getAndIncreaseSeq(String key) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("key", key);
		map.put("area", "*");
		map.put("date", "*");

		Integer seq = seqRepository.selectOne(map);
		if (seq == null) {
			seqRepository.insertSeq(map);
			return 0;
		} else {
			seqRepository.updateSeq(map);
			return seq + 1;
		}
	}

	public int getLock(String orgId, String paramKey) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("paramKey", paramKey);
		map.put("orgId", orgId);
		Integer status = seqRepository.selectLockStatus(map);

		if (status == null) {
			status = 0;
		}
		return status;
	}

	public int setLock(String orgId, String paramKey, int lockStauts) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("paramKey", paramKey);
		map.put("orgId", orgId);
		map.put("lockStauts", lockStauts);

		return seqRepository.updateLockStatus(map);
	}

}
